package logic

import (
	"context"
	"github.com/golang-jwt/jwt/v4"
	"time"

	"auth/internal/svc"
	"auth/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginRsp, err error) {
	// todo: add your logic here and delete this line
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	accessSecret := l.svcCtx.Config.Auth.AccessSecret

	token, err := l.getJwtToken(accessSecret, now, accessExpire, req.Username)
	if err != nil {
		return nil, err
	}

	return &types.LoginRsp{
		Jwt:    token,
		Expire: now + accessExpire,
	}, nil
}

func (l *LoginLogic) getJwtToken(secretKey string, iat, seconds int64, username string) (string, error) {
	claims := jwt.MapClaims{
		"exp":      iat + seconds,
		"iat":      iat,
		"username": username,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(secretKey))
}
